

import os
import threading
from time import sleep
import tempfile
import subprocess
from Tkinter import TclError
import sys

from vk2ftp import get_ftpd, AdvancedVkontakte
from gui import ask_captcha, GUI, show_error



class TkThreadAccess:

	def __init__(self):
		self.jobs = []
	
	def wrap(self, func):
		lock = threading.Event()
		val = {}
		def tmp1(*args, **kw):
			def tmp2():
				val[None] = func(*args, **kw)
				lock.set()
			self.do(tmp2)
			lock.wait()
			lock.clear()
			return val[None]
			
		return tmp1
		
	
	def do(self, func):
		self.jobs.append(func)
	
	def update(self):
		while self.jobs:
			self.jobs.pop(0)()
	
	def mainloop_with_root(self, root):
		while True:
			root.update()
			self.update()
			sleep(0.1)



def run_parallel():
	
	home_dir = os.path.expanduser('~')
	home_file = os.path.join(home_dir, '.evlum')

	avk = AdvancedVkontakte()
	

	if os.path.exists(home_file):
		f = open(home_file, 'r')
		user, pwd = f.read().split(' ')
		f.close()
	
		avk.login(user, pwd)
	else:
	
		val = avk.register(tkaccess.wrap(ask_captcha))
		if val is None:
			sys.exit()
		user, pwd = val

		f = open(home_file, 'w')
		f.write(user+' '+pwd)
		f.close()
	
	ftpd = get_ftpd(ftp_dir, avk, on_block=tkaccess.wrap(gui.disable), on_unblock=tkaccess.wrap(gui.enable))
	
	tkaccess.do(gui.enable)
	
	ftpd.serve_forever()



def run_ftp_client(query):
	dir = os.path.join(ftp_dir, query)
	if not os.path.exists(dir):
		os.mkdir(dir)
	try:
		subprocess.Popen(['explorer', 'ftp://127.0.0.1:2121/'+query])
	except OSError:
		subprocess.Popen(['nautilus', 'ftp://anonymous@127.0.0.1:2121'])



sys.excepthook = lambda a, b, c: show_error(b)

#avk = AdvancedVkontakte()
#print avk.register(ask_captcha)
#assert False

gui = GUI(run_ftp_client)
gui.disable()
tkaccess = TkThreadAccess()
ftp_dir = tempfile.mkdtemp()

t = threading.Thread(target=run_parallel)
t.daemon = True
t.start()

try:
	tkaccess.mainloop_with_root(gui)
except TclError, exc:
	print exc
	sys.exit()








